package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Contract;
import com.zhentao.pojo.ContractItem;
import com.zhentao.pojo.ContractTemplate;
import com.zhentao.service.ContractItemService;
import com.zhentao.service.ContractService;
import com.zhentao.service.ContractTemplateService;
import com.zhentao.util.Result;
import com.zhentao.vo.ContractQueryVO;
import com.zhentao.vo.ContractTemplateVO;
import com.zhentao.vo.ContractVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zhentao.mapper.ContractItemMapper;
import com.zhentao.vo.ContractItemVO;
import java.util.stream.Collectors;

/**
 * 合同管理Controller
 * @date: 2025/8/13 20:05
 * @author: ftt
 */
@RestController
@RequestMapping("/contract")
@CrossOrigin
public class ContractController {

    @Autowired
    private ContractService contractService;
    
    @Autowired
    private ContractItemService contractItemService;

    @Autowired
    private ContractTemplateService contractTemplateService;

    @Autowired
    private ContractItemMapper contractItemMapper;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("合同管理服务正常运行");
    }

    /**
     * 分页查询合同列表
     */
    @PostMapping("/page")
    public Result<IPage<ContractVO>> getContractPage(@RequestBody ContractQueryVO queryVO) {
        try {
            Page<Contract> page = new Page<>(queryVO.getCurrent(), queryVO.getSize());
            QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
            
            if (queryVO.getContractNo() != null && !queryVO.getContractNo().trim().isEmpty()) {
                queryWrapper.like("contract_no", queryVO.getContractNo());
            }
            if (queryVO.getContractName() != null && !queryVO.getContractName().trim().isEmpty()) {
                queryWrapper.like("contract_name", queryVO.getContractName());
            }
            if (queryVO.getContractType() != null && !queryVO.getContractType().trim().isEmpty()) {
                queryWrapper.eq("contract_type", queryVO.getContractType());
            }
            if (queryVO.getCustomerId() != null) {
                queryWrapper.eq("customer_id", queryVO.getCustomerId());
            }
            if (queryVO.getSupplierId() != null) {
                queryWrapper.eq("supplier_id", queryVO.getSupplierId());
            }
            if (queryVO.getStatus() != null) {
                queryWrapper.eq("status", queryVO.getStatus());
            }
            if (queryVO.getStartDate() != null) {
                queryWrapper.ge("signed_date", queryVO.getStartDate());
            }
            if (queryVO.getEndDate() != null) {
                queryWrapper.le("signed_date", queryVO.getEndDate());
            }
            
            queryWrapper.orderByDesc("create_time");
            
            IPage<Contract> contractPage = contractService.page(page, queryWrapper);
            
            // 转换为VO
            IPage<ContractVO> voPage = new Page<>(contractPage.getCurrent(), contractPage.getSize(), contractPage.getTotal());
            List<ContractVO> voList = new ArrayList<>();
            for (Contract contract : contractPage.getRecords()) {
                voList.add(convertToVO(contract));
            }
            voPage.setRecords(voList);
            
            return Result.success(voPage);
        } catch (Exception e) {
            return Result.error("查询合同列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询合同详情
     */
    @GetMapping("/{id}")
    public Result<ContractVO> getContractById(@PathVariable Long id) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            ContractVO vo = convertToVO(contract);
            
            // 查询合同明细（包含产品信息）
            List<ContractItemVO> items = contractItemMapper.selectContractItemsWithProduct(id);
            vo.setContractItems(items);
            
            return Result.success(vo);
        } catch (Exception e) {
            return Result.error("查询合同详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增合同
     */
    @PostMapping
    public Result<String> addContract(@RequestBody ContractVO contractVO) {
        try {
            // 数据验证
            if (contractVO.getContractName() == null || contractVO.getContractName().trim().isEmpty()) {
                return Result.error("合同名称不能为空");
            }
            if (contractVO.getContractType() == null || contractVO.getContractType().trim().isEmpty()) {
                return Result.error("合同类型不能为空");
            }
            if (contractVO.getSignedDate() == null) {
                return Result.error("签订日期不能为空");
            }
            if (contractVO.getStartDate() == null) {
                return Result.error("开始日期不能为空");
            }
            if (contractVO.getEndDate() == null) {
                return Result.error("结束日期不能为空");
            }
            if (contractVO.getTotalAmount() == null || contractVO.getTotalAmount().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return Result.error("合同金额必须大于0");
            }
            
            // 日期验证
            if (contractVO.getStartDate().after(contractVO.getEndDate())) {
                return Result.error("开始日期不能晚于结束日期");
            }
            
            // 生成合同编号
            contractVO.setContractNo(generateContractNo());
            contractVO.setStatus(0); // 草稿状态
            contractVO.setCreateTime(new Date());
            contractVO.setUpdateTime(new Date());
            
            // 转换为Contract实体
            Contract contract = new Contract();
            contract.setContractNo(contractVO.getContractNo());
            contract.setContractName(contractVO.getContractName());
            contract.setContractType(contractVO.getContractType());
            contract.setCustomerId(contractVO.getCustomerId());
            contract.setSupplierId(contractVO.getSupplierId());
            contract.setTotalAmount(contractVO.getTotalAmount());
            contract.setSignedDate(contractVO.getSignedDate());
            contract.setStartDate(contractVO.getStartDate());
            contract.setEndDate(contractVO.getEndDate());
            contract.setStatus(contractVO.getStatus());
            contract.setRemark(contractVO.getRemark());
            contract.setTenantId(contractVO.getTenantId());
            contract.setCreateTime(contractVO.getCreateTime());
            contract.setUpdateTime(contractVO.getUpdateTime());
            
            // 保存合同主表
            boolean saved = contractService.save(contract);
            if (!saved) {
                return Result.error("保存合同失败");
            }
            
            // 保存合同明细
            if (contractVO.getContractItems() != null && !contractVO.getContractItems().isEmpty()) {
                List<ContractItem> items = new ArrayList<>();
                for (ContractItemVO itemVO : contractVO.getContractItems()) {
                    ContractItem item = new ContractItem();
                    item.setContractId(contract.getId());
                    item.setProductId(itemVO.getProductId());
                    item.setQuantity(itemVO.getQuantity());
                    item.setUnitPrice(itemVO.getUnitPrice());
                    item.setRemark(itemVO.getRemark());
                    if (item.getQuantity() != null && item.getUnitPrice() != null) {
                        item.setTotalAmount(item.getQuantity().multiply(item.getUnitPrice()));
                    }
                    items.add(item);
                }
                contractItemService.saveBatch(items);
            }
            
            return Result.success("合同创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建合同失败：" + e.getMessage());
        }
    }

    /**
     * 更新合同
     */
    @PutMapping("/{id}")
    public Result<String> updateContract(@PathVariable Long id, @RequestBody ContractVO contractVO) {
        try {
            Contract existingContract = contractService.getById(id);
            if (existingContract == null) {
                return Result.error("合同不存在");
            }
            
            // 只有草稿状态的合同可以修改
            if (existingContract.getStatus() != 0) {
                return Result.error("只有草稿状态的合同可以修改");
            }
            
            contractVO.setId(id);
            contractVO.setUpdateTime(new Date());
            
            // 更新合同主表
            boolean updated = contractService.updateById(contractVO);
            if (!updated) {
                return Result.error("更新合同失败");
            }
            
            // 删除原有明细，重新保存
            QueryWrapper<ContractItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("contract_id", id);
            contractItemService.remove(itemWrapper);
            
            if (contractVO.getContractItems() != null && !contractVO.getContractItems().isEmpty()) {
                List<ContractItem> items = new ArrayList<>();
                for (ContractItemVO itemVO : contractVO.getContractItems()) {
                    ContractItem item = new ContractItem();
                    item.setContractId(id);
                    item.setProductId(itemVO.getProductId());
                    item.setQuantity(itemVO.getQuantity());
                    item.setUnitPrice(itemVO.getUnitPrice());
                    item.setRemark(itemVO.getRemark());
                    if (item.getQuantity() != null && item.getUnitPrice() != null) {
                        item.setTotalAmount(item.getQuantity().multiply(item.getUnitPrice()));
                    }
                    items.add(item);
                }
                contractItemService.saveBatch(items);
            }
            
            return Result.success("合同更新成功");
        } catch (Exception e) {
            return Result.error("更新合同失败：" + e.getMessage());
        }
    }

    /**
     * 删除合同
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteContract(@PathVariable Long id) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            // 只有草稿状态的合同可以删除
            if (contract.getStatus() != 0) {
                return Result.error("只有草稿状态的合同可以删除");
            }
            
            // 删除合同明细
            QueryWrapper<ContractItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("contract_id", id);
            contractItemService.remove(itemWrapper);
            
            // 删除合同主表
            boolean removed = contractService.removeById(id);
            if (!removed) {
                return Result.error("删除合同失败");
            }
            
            return Result.success("合同删除成功");
        } catch (Exception e) {
            return Result.error("删除合同失败：" + e.getMessage());
        }
    }

    /**
     * 提交审批
     */
    @PostMapping("/{id}/submit")
    public Result<String> submitForApproval(@PathVariable Long id) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            if (contract.getStatus() != 0) {
                return Result.error("只有草稿状态的合同可以提交审批");
            }
            
            contract.setStatus(1); // 待审批状态
            contract.setUpdateTime(new Date());
            
            boolean updated = contractService.updateById(contract);
            if (!updated) {
                return Result.error("提交审批失败");
            }
            
            return Result.success("合同已提交审批");
        } catch (Exception e) {
            return Result.error("提交审批失败：" + e.getMessage());
        }
    }

    /**
     * 审批通过
     */
    @PostMapping("/{id}/approve")
    public Result<String> approveContract(@PathVariable Long id) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            if (contract.getStatus() != 1) {
                return Result.error("只有待审批状态的合同可以审批");
            }
            
            contract.setStatus(2); // 生效状态
            contract.setUpdateTime(new Date());
            
            boolean updated = contractService.updateById(contract);
            if (!updated) {
                return Result.error("审批失败");
            }
            
            return Result.success("合同审批通过");
        } catch (Exception e) {
            return Result.error("审批失败：" + e.getMessage());
        }
    }

    /**
     * 审批拒绝
     */
    @PostMapping("/{id}/reject")
    public Result<String> rejectContract(@PathVariable Long id, @RequestParam String reason) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            if (contract.getStatus() != 1) {
                return Result.error("只有待审批状态的合同可以审批");
            }
            
            contract.setStatus(0); // 退回草稿状态
            contract.setRemark(reason);
            contract.setUpdateTime(new Date());
            
            boolean updated = contractService.updateById(contract);
            if (!updated) {
                return Result.error("审批拒绝失败");
            }
            
            return Result.success("合同审批已拒绝");
        } catch (Exception e) {
            return Result.error("审批拒绝失败：" + e.getMessage());
        }
    }

    /**
     * 完成合同
     */
    @PostMapping("/{id}/complete")
    public Result<String> completeContract(@PathVariable Long id) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            if (contract.getStatus() != 2) {
                return Result.error("只有生效状态的合同可以完成");
            }
            
            contract.setStatus(3); // 完成状态
            contract.setUpdateTime(new Date());
            
            boolean updated = contractService.updateById(contract);
            if (!updated) {
                return Result.error("完成合同失败");
            }
            
            return Result.success("合同已完成");
        } catch (Exception e) {
            return Result.error("完成合同失败：" + e.getMessage());
        }
    }

    /**
     * 终止合同
     */
    @PostMapping("/{id}/terminate")
    public Result<String> terminateContract(@PathVariable Long id, @RequestParam String reason) {
        try {
            Contract contract = contractService.getById(id);
            if (contract == null) {
                return Result.error("合同不存在");
            }
            
            if (contract.getStatus() != 2) {
                return Result.error("只有生效状态的合同可以终止");
            }
            
            contract.setStatus(4); // 终止状态
            contract.setRemark(reason);
            contract.setUpdateTime(new Date());
            
            boolean updated = contractService.updateById(contract);
            if (!updated) {
                return Result.error("终止合同失败");
            }
            
            return Result.success("合同已终止");
        } catch (Exception e) {
            return Result.error("终止合同失败：" + e.getMessage());
        }
    }

    /**
     * 获取合同状态列表
     */
    @GetMapping("/status/list")
    public Result<List<Map<String, Object>>> getContractStatusList() {
        try {
            List<Map<String, Object>> statusList = new ArrayList<>();
            Map<String, Object> status0 = new HashMap<>();
            status0.put("value", 0);
            status0.put("label", "草稿");
            statusList.add(status0);
            
            Map<String, Object> status1 = new HashMap<>();
            status1.put("value", 1);
            status1.put("label", "待审批");
            statusList.add(status1);
            
            Map<String, Object> status2 = new HashMap<>();
            status2.put("value", 2);
            status2.put("label", "生效");
            statusList.add(status2);
            
            Map<String, Object> status3 = new HashMap<>();
            status3.put("value", 3);
            status3.put("label", "完成");
            statusList.add(status3);
            
            Map<String, Object> status4 = new HashMap<>();
            status4.put("value", 4);
            status4.put("label", "终止");
            statusList.add(status4);
            
            return Result.success(statusList);
        } catch (Exception e) {
            return Result.error("获取状态列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取合同类型列表
     */
    @GetMapping("/type/list")
    public Result<List<Map<String, Object>>> getContractTypeList() {
        try {
            List<Map<String, Object>> typeList = new ArrayList<>();
            Map<String, Object> saleType = new HashMap<>();
            saleType.put("value", "SALE");
            saleType.put("label", "销售合同");
            typeList.add(saleType);
            
            Map<String, Object> purchaseType = new HashMap<>();
            purchaseType.put("value", "PURCHASE");
            purchaseType.put("label", "采购合同");
            typeList.add(purchaseType);
            
            return Result.success(typeList);
        } catch (Exception e) {
            return Result.error("获取类型列表失败：" + e.getMessage());
        }
    }

    /**
     * 转换为VO
     */
    private ContractVO convertToVO(Contract contract) {
        ContractVO vo = new ContractVO();
        // 复制基本属性
        vo.setId(contract.getId());
        vo.setContractNo(contract.getContractNo());
        vo.setContractName(contract.getContractName());
        vo.setContractType(contract.getContractType());
        vo.setCustomerId(contract.getCustomerId());
        vo.setSupplierId(contract.getSupplierId());
        vo.setTotalAmount(contract.getTotalAmount());
        vo.setSignedDate(contract.getSignedDate());
        vo.setStartDate(contract.getStartDate());
        vo.setEndDate(contract.getEndDate());
        vo.setStatus(contract.getStatus());
        vo.setRemark(contract.getRemark());
        vo.setTenantId(contract.getTenantId());
        vo.setCreateUser(contract.getCreateUser());
        vo.setCreateTime(contract.getCreateTime());
        vo.setUpdateTime(contract.getUpdateTime());
        
        // 设置状态名称
        switch (contract.getStatus()) {
            case 0:
                vo.setStatusName("草稿");
                break;
            case 1:
                vo.setStatusName("待审批");
                break;
            case 2:
                vo.setStatusName("生效");
                break;
            case 3:
                vo.setStatusName("完成");
                break;
            case 4:
                vo.setStatusName("终止");
                break;
            default:
                vo.setStatusName("未知");
                break;
        }
        
        // 设置合同类型名称
        switch (contract.getContractType()) {
            case "SALE":
                vo.setContractTypeName("销售合同");
                break;
            case "PURCHASE":
                vo.setContractTypeName("采购合同");
                break;
            default:
                vo.setContractTypeName("未知");
                break;
        }
        
        return vo;
    }

    /**
     * 生成合同编号
     */
    private String generateContractNo() {
        return "CT" + System.currentTimeMillis();
    }

    // ==================== 合同模板相关API ====================

    /**
     * 获取合同模板列表
     */
    @GetMapping("/template/list")
    public Result<List<ContractTemplateVO>> getContractTemplateList(@RequestParam(required = false) String templateType) {
        try {
            QueryWrapper<ContractTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_enabled", 1); // 只查询启用的模板
            
            if (templateType != null && !templateType.trim().isEmpty()) {
                queryWrapper.eq("template_type", templateType);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            List<ContractTemplate> templates = contractTemplateService.list(queryWrapper);
            List<ContractTemplateVO> voList = new ArrayList<>();
            
            for (ContractTemplate template : templates) {
                voList.add(convertTemplateToVO(template));
            }
            
            return Result.success(voList);
        } catch (Exception e) {
            return Result.error("获取合同模板列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询合同模板
     */
    @PostMapping("/template/page")
    public Result<IPage<ContractTemplateVO>> getContractTemplatePage(@RequestBody Map<String, Object> params) {
        try {
            // 构建查询条件
            QueryWrapper<ContractTemplate> wrapper = new QueryWrapper<>();
            
            // 模板名称模糊查询
            if (params.get("templateName") != null && !params.get("templateName").toString().trim().isEmpty()) {
                wrapper.like("template_name", params.get("templateName").toString().trim());
            }
            
            // 模板类型查询
            if (params.get("templateType") != null && !params.get("templateType").toString().trim().isEmpty()) {
                wrapper.eq("template_type", params.get("templateType").toString().trim());
            }
            
            // 启用状态查询
            if (params.get("isEnabled") != null) {
                wrapper.eq("is_enabled", params.get("isEnabled"));
            }
            
            // 按创建时间倒序
            wrapper.orderByDesc("create_time");
            
            // 分页查询
            Integer current = (Integer) params.get("current");
            Integer size = (Integer) params.get("size");
            if (current == null) current = 1;
            if (size == null) size = 10;
            
            Page<ContractTemplate> page = new Page<>(current, size);
            IPage<ContractTemplate> templatePage = contractTemplateService.page(page, wrapper);
            
            // 转换为VO
            IPage<ContractTemplateVO> voPage = new Page<>(current, size);
            voPage.setTotal(templatePage.getTotal());
            voPage.setPages(templatePage.getPages());
            
            List<ContractTemplateVO> voList = templatePage.getRecords().stream()
                .map(this::convertTemplateToVO)
                .collect(Collectors.toList());
            voPage.setRecords(voList);
            
            return Result.success(voPage);
        } catch (Exception e) {
            return Result.error("查询合同模板列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取合同模板详情
     */
    @GetMapping("/template/{id}")
    public Result<ContractTemplateVO> getContractTemplateById(@PathVariable Long id) {
        try {
            ContractTemplate template = contractTemplateService.getById(id);
            if (template == null) {
                return Result.error("合同模板不存在");
            }
            
            return Result.success(convertTemplateToVO(template));
        } catch (Exception e) {
            return Result.error("获取合同模板详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增合同模板
     */
    @PostMapping("/template")
    public Result<String> addContractTemplate(@RequestBody ContractTemplateVO templateVO) {
        try {
            // 数据验证
            if (templateVO.getTemplateName() == null || templateVO.getTemplateName().trim().isEmpty()) {
                return Result.error("模板名称不能为空");
            }
            if (templateVO.getTemplateType() == null || templateVO.getTemplateType().trim().isEmpty()) {
                return Result.error("模板类型不能为空");
            }
            if (templateVO.getTemplateContent() == null || templateVO.getTemplateContent().trim().isEmpty()) {
                return Result.error("模板内容不能为空");
            }
            
            ContractTemplate template = new ContractTemplate();
            template.setTemplateName(templateVO.getTemplateName());
            template.setTemplateType(templateVO.getTemplateType());
            template.setTemplateContent(templateVO.getTemplateContent());
            template.setDescription(templateVO.getDescription());
            template.setIsEnabled(templateVO.getIsEnabled() != null ? templateVO.getIsEnabled() : 1);
            template.setTenantId(templateVO.getTenantId());
            template.setCreateUser(templateVO.getCreateUser());
            template.setCreateTime(new Date());
            template.setUpdateTime(new Date());
            
            boolean saved = contractTemplateService.save(template);
            if (!saved) {
                return Result.error("保存合同模板失败");
            }
            
            return Result.success("合同模板创建成功");
        } catch (Exception e) {
            return Result.error("创建合同模板失败：" + e.getMessage());
        }
    }

    /**
     * 更新合同模板
     */
    @PutMapping("/template/{id}")
    public Result<String> updateContractTemplate(@PathVariable Long id, @RequestBody ContractTemplateVO templateVO) {
        try {
            ContractTemplate existingTemplate = contractTemplateService.getById(id);
            if (existingTemplate == null) {
                return Result.error("合同模板不存在");
            }
            
            // 数据验证
            if (templateVO.getTemplateName() == null || templateVO.getTemplateName().trim().isEmpty()) {
                return Result.error("模板名称不能为空");
            }
            if (templateVO.getTemplateType() == null || templateVO.getTemplateType().trim().isEmpty()) {
                return Result.error("模板类型不能为空");
            }
            if (templateVO.getTemplateContent() == null || templateVO.getTemplateContent().trim().isEmpty()) {
                return Result.error("模板内容不能为空");
            }
            
            existingTemplate.setTemplateName(templateVO.getTemplateName());
            existingTemplate.setTemplateType(templateVO.getTemplateType());
            existingTemplate.setTemplateContent(templateVO.getTemplateContent());
            existingTemplate.setDescription(templateVO.getDescription());
            existingTemplate.setIsEnabled(templateVO.getIsEnabled());
            existingTemplate.setUpdateTime(new Date());
            
            boolean updated = contractTemplateService.updateById(existingTemplate);
            if (!updated) {
                return Result.error("更新合同模板失败");
            }
            
            return Result.success("合同模板更新成功");
        } catch (Exception e) {
            return Result.error("更新合同模板失败：" + e.getMessage());
        }
    }

    /**
     * 删除合同模板
     */
    @DeleteMapping("/template/{id}")
    public Result<String> deleteContractTemplate(@PathVariable Long id) {
        try {
            ContractTemplate template = contractTemplateService.getById(id);
            if (template == null) {
                return Result.error("合同模板不存在");
            }
            
            boolean deleted = contractTemplateService.removeById(id);
            if (!deleted) {
                return Result.error("删除合同模板失败");
            }
            
            return Result.success("合同模板删除成功");
        } catch (Exception e) {
            return Result.error("删除合同模板失败：" + e.getMessage());
        }
    }

    /**
     * 根据模板创建合同
     */
    @PostMapping("/create-from-template/{templateId}")
    public Result<ContractVO> createContractFromTemplate(@PathVariable Long templateId, @RequestBody ContractVO contractVO) {
        try {
            ContractTemplate template = contractTemplateService.getById(templateId);
            if (template == null) {
                return Result.error("合同模板不存在");
            }
            
            if (template.getIsEnabled() != 1) {
                return Result.error("该合同模板已禁用");
            }
            
            // 使用模板内容初始化合同
            contractVO.setContractName(contractVO.getContractName() != null ? contractVO.getContractName() : template.getTemplateName());
            contractVO.setContractType(template.getTemplateType());
            contractVO.setRemark(template.getTemplateContent());
            
            // 生成合同编号
            contractVO.setContractNo(generateContractNo());
            contractVO.setStatus(0); // 草稿状态
            contractVO.setCreateTime(new Date());
            contractVO.setUpdateTime(new Date());
            
            // 转换为Contract实体
            Contract contract = new Contract();
            contract.setContractNo(contractVO.getContractNo());
            contract.setContractName(contractVO.getContractName());
            contract.setContractType(contractVO.getContractType());
            contract.setCustomerId(contractVO.getCustomerId());
            contract.setSupplierId(contractVO.getSupplierId());
            contract.setTotalAmount(contractVO.getTotalAmount());
            contract.setSignedDate(contractVO.getSignedDate());
            contract.setStartDate(contractVO.getStartDate());
            contract.setEndDate(contractVO.getEndDate());
            contract.setStatus(contractVO.getStatus());
            contract.setRemark(contractVO.getRemark());
            contract.setTenantId(contractVO.getTenantId());
            contract.setCreateTime(contractVO.getCreateTime());
            contract.setUpdateTime(contractVO.getUpdateTime());
            
            // 保存合同主表
            boolean saved = contractService.save(contract);
            if (!saved) {
                return Result.error("保存合同失败");
            }
            
            // 保存合同明细
            if (contractVO.getContractItems() != null && !contractVO.getContractItems().isEmpty()) {
                List<ContractItem> items = new ArrayList<>();
                for (ContractItemVO itemVO : contractVO.getContractItems()) {
                    ContractItem item = new ContractItem();
                    item.setContractId(contract.getId());
                    item.setProductId(itemVO.getProductId());
                    item.setQuantity(itemVO.getQuantity());
                    item.setUnitPrice(itemVO.getUnitPrice());
                    item.setRemark(itemVO.getRemark());
                    if (item.getQuantity() != null && item.getUnitPrice() != null) {
                        item.setTotalAmount(item.getQuantity().multiply(item.getUnitPrice()));
                    }
                    items.add(item);
                }
                contractItemService.saveBatch(items);
            }
            
            // 返回创建的合同VO
            ContractVO createdContractVO = convertToVO(contract);
            return Result.success(createdContractVO);
        } catch (Exception e) {
            return Result.error("根据模板创建合同失败：" + e.getMessage());
        }
    }

    /**
     * 转换为模板VO
     */
    private ContractTemplateVO convertTemplateToVO(ContractTemplate template) {
        ContractTemplateVO vo = new ContractTemplateVO();
        vo.setId(template.getId());
        vo.setTemplateName(template.getTemplateName());
        vo.setTemplateType(template.getTemplateType());
        vo.setTemplateContent(template.getTemplateContent());
        vo.setDescription(template.getDescription());
        vo.setIsEnabled(template.getIsEnabled());
        vo.setTenantId(template.getTenantId());
        vo.setCreateUser(template.getCreateUser());
        vo.setCreateTime(template.getCreateTime());
        vo.setUpdateTime(template.getUpdateTime());
        
        // 设置模板类型名称
        switch (template.getTemplateType()) {
            case "SALE":
                vo.setTemplateTypeName("销售合同模板");
                break;
            case "PURCHASE":
                vo.setTemplateTypeName("采购合同模板");
                break;
            default:
                vo.setTemplateTypeName("未知");
                break;
        }
        
        // 设置启用状态名称
        vo.setIsEnabledName(template.getIsEnabled() == 1 ? "启用" : "禁用");
        
        return vo;
    }
}
